<template>
  <div v-loading="loading">
    <el-form ref="form" :model="pojo" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-for="(item, index) in rootItemInfo" :key="'form' + index + item.field" :span="parseInt(item.fieldGrid)">
          <online-query-form-item
            v-if="express(item)"
            :key="index"
            :item="item"
            :query-param="pojo"
            :dict-options="item.dict"
            :index="index"
            :verify="getVerify(item)"
          />
        </el-col>
        <!-- 子表单 -->
        <el-col v-show="subItemInfo.length > 0" :span="24">
          <OnlineSubForm
            v-for="sub in subItemInfo"
            :key="`subForm${sub.key}`"
            :ref="sub.key"
            :properties="sub"
            :form-pojo="pojo"
            :is-button="false"
          />
        </el-col>
      </el-row>
      <!-- 附件列表 -->
      <el-row>
        <el-col v-if="config.isFile == '1'" :span="24">
          <FileTable :list.sync="pojo.filelist" :data-type="config.fileDataType" :btn-show="!otherBtnHide" />
        </el-col>
      </el-row>
    </el-form>
    <div v-show="footerShow" slot="footer" class="dialog-footer" style="text-align: right">
      <!--保存 取消按钮-->
      <el-button v-if="refType" type="primary" @click="confirmHandle">{{ $t('确认') }}</el-button>
      <save-btn v-else :cancel-func="cancel" />
    </div>
  </div>
</template>

<script>
import OnlineQueryFormItem from '@/components/desform/online/OnlineQueryFormItem.vue'
import {
  requestAll,
  requestMethod
} from '@/api/system/desform/onlineForm/onlCgformHead'
import {
  fieldDefaulfVal
} from '@/components/desform/online/onlineUtils'
import { mapState } from 'vuex'
import { masterJudge, watchMasterPropComputed } from '@/components/desform/online/onlineUtils.js'
import { getRules } from '@/views/system/desform/release/formDataProperty.js'

export default {
  components: {
    OnlineQueryFormItem,
    OnlineSubForm: () => import('@/components/desform/online/OnlineSubForm.vue')
  },
  props: {
    refType: {
      type: Boolean,
      default: () => false,
      required: false
    }
  },
  data() {
    return {
      loading: true,
      subTabShow: false,
      otherBtnHide: false,
      queryId: this.$route.query.queryId || '',
      // 请求对象
      requestPojo: {
        getOnlineFormItem: '/head/OnlineApiTest/api/getBtnDisplayItem/',
        getOnlineFormItemData: '/head/OnlineApiTest/api/form/',
        postAutoForm: '/head/OnlineApiTest/api/formAdd/' + this.$route.query.queryId
      },
      rules: {},
      rootItemInfo: [], // 主表信息
      subItemInfo: [], // 子表信息
      pojo: {}, // 表单对象
      config: {}, // 配置信息
      menuKey: 'onlinefrom', // 菜单标识
      dealId: this.$route.query.id || '', // 在项目里这个并不为空
      footerShow: true,
      data: {} // 流程组件数据
    }
  },
  computed: {
    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0
        var v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    },
    pojoProp() {
          return watchMasterPropComputed(this.pojo, this.rootItemInfo)
    },
     ...mapState('dbAbout', ['head', 'tempId'])

  },
   watch: {
        pojoProp: {
          handler() {
              this.express()
          },
          deep: true
      }
    },
  created() {
      this.$bus.$emit('async_done')
      if (this.tempId) {
        this.queryId = this.$route.query.queryId
      }
  },
  methods: {
    init(data, btnCode) {
      console.log('行--数据', data)
      if (data != null && data.id !== undefined) {
        this.getFormItem(btnCode.btnCode).then(() => {
          if ((btnCode.tbName && data[btnCode.tbName]) && this.refType) { // 子表回显数据
                  if (data[btnCode.tbName] instanceof Array) {
                      this.pojo = data[btnCode.tbName][0]
                  } else {
                      this.pojo = data[btnCode.tbName]
                  }
          } else {
               // 这里其实维护完按钮数据就不应该显示数据了
               if (!this.refType) {
                   this.initFormData(data)
               }
          }
          this.requestPojo.postAutoForm = `/head/OnlineApiTest/api/btnFormEdit/${this.queryId}/${btnCode.btnCode}`
        })
      } else {
        this.reset(btnCode, data)
        // this.requestPojo.postAutoForm = '/head/OnlineApiTest/api/formAdd/' + this.queryId
      }
    },
    getFormItem(data) { // 查询当前表显示的item
      return new Promise((resolve) => {
        this.loading = true
        requestAll(`${this.requestPojo.getOnlineFormItem}${this.queryId}/${data}`).then(response => {
          // 配置信息
          this.config = response.data.configuation
          const resData = response.data
          const subInfo = []
          const rootInfo = []
          // 处理返回来的参数
          if (resData) {
            // 循环对象属性
            Object.keys(resData).map((key) => {
              const item = resData[key]
              if (item.view === 'tab') {
                // 封装子表对象
                subInfo.push(item)
                if (item.relationType === 2) { // 一对多
                  // 将 主子表数据封装一个对象 （elementui 校验）
                  this.$set(this.pojo, item.key, [])
                  this.disposeSubInfo(item)
                } else if (item.relationType === 1) { // 一对一
                  const subProp = {}
                  item.properties.map(e => {
                    subProp[e.field] = fieldDefaulfVal(e.delVal)
                  })
                  this.$set(this.pojo, item.key, subProp)
                }
              } else {
                // 为表单对象赋值
                if (item.field) {
                  this.$set(this.pojo, item.field, fieldDefaulfVal(item.delVal))
                  rootInfo.push(item)
                }
              }
            })
          }
          // 主表信息赋值
          this.rootItemInfo = rootInfo
          if (subInfo.length > 0) {
            subInfo.sort((one, next) => {
              return one.order - next.order
            })
            this.subItemInfo = [...subInfo]
          } else {
            this.subItemInfo = []
          }
          this.rootItemInfo = rootInfo
          this.subItemInfo = subInfo
          resolve(data)
          this.loading = false
        })
      })
    },
    // 添加功能
    submitForm(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.rootItemInfo.map(el => {
              if (el.view === 'hide') {
                // 如果是项目 或者基金 赋值 id
                this.pojo[el.field] = this.$route.query.id
              }
            })
            const data = this.disposeParams(this.rootItemInfo)
            const submitFormData = Object.assign({}, this.pojo, data)
            this.getAllSubFormOrTable(1).then(resData => {
              if (resData.length > 0) {
                resData.map(vm => {
                  const tempSubDataArr = []
                  tempSubDataArr.push(this.pojo[vm.refName])
                  submitFormData[vm.refName] = tempSubDataArr
                })
              }
            })
            this.getAllSubFormOrTable(2).then(resData => {
                if (resData.length > 0) {
                       resData.forEach(vm => {
                           // 子表数组
                           const tempSubDataArr = []
                           const dataArr = vm[0].pojo[vm.refName]
                           // TODO 这里需要优化 如果能直接绑定pojo就不用这么麻烦了
                           dataArr.map(row => { // 每行数据
                              const rowData = {}
                                  row.map(col => { // 每个单元格的数据
                                      if (Array.isArray(col[col.field])) { // 是多选下拉框
                                           rowData[col.field] = col[col.field].toString()
                                      } else {
                                           rowData[col.field] = col[col.field]
                                      }
                                })
                               const extra = Object.assign({}, row)
                               Object.keys(extra).map((key) => {
                                  // 这里需要优化 自定义按钮赋值问题
                                  if (isNaN(key) && extra[key] instanceof Object) {
                                    rowData[key] = extra[key]
                                  } else if (key === 'id') {
                                      rowData[key] = extra[key]
                                  }
                               })
                              tempSubDataArr.push(rowData)
                           })
                             submitFormData[vm.refName] = tempSubDataArr
                       })
                    }
                 })
              console.log('提交数据', submitFormData)
            requestMethod(`${this.requestPojo.postAutoForm}`, 'post', submitFormData).then(response => {
              if (response.code === 200) {
                if (type === 'process') {
                  // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                  this.pojo.id = response.data
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  this.closeForm()
                }
                resolve(response.data)
              } else {
                this.msgError(response.msg)
                reject()
              }
              this.loading = false
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      })
    },
    disposeSubInfo(subInfo) {
      // 将单选改为下拉框
      subInfo.columns.forEach(column => {
        if (column.view === 'radio') {
          column.view = 'list'
        }
      })
    },
    disposeParams(arrParm) { // 处理一下提交的对象
      const subObj = {}
      arrParm.forEach(root => {
        if (root.view === 'choose') {
          subObj[root.field] = this.pojo[root.field].toString()
        } else {
          subObj[root.field] = this.pojo[root.field]
        }
      })
      return subObj
    },
    getAllSubFormOrTable(arg) { // 获取所有的一对一表单或一对多行编辑
      const arr = []
      const that = this
      for (const i of this.subItemInfo) {
        if (arg === 1) {
          // 一对一
          if (i.relationType === 1) {
            arr.push(this.getRefPromise(that, i.key))
          }
        } else {
          // 一对多
          if (i.relationType !== 1) {
            arr.push(this.getRefPromise(that, i.key))
          }
        }
      }
      return Promise.all(arr)
    },
    getRefPromise(vm, name) { // 同步根据名字得到dom
      return new Promise((resolve) => {
        (function next() {
          const ref = vm.$refs[name]
          ref.refName = name
          if (ref) {
            resolve(ref)
          } else {
            setTimeout(() => {
              next()
            }, 10)
          }
        })()
      })
    },
    reset(data, rowData) { // 清空表单项
      this.getFormItem(data.btnCode).then(() => {
        if (this.config?.isFile) {
          this.pojo['filelist'] = this.config.optionFileList
          this.$forceUpdate()
        }
        // 子表点击按钮赋值
        if (this.refType && rowData[data.tbName]) {
            this.pojo = rowData[data.tbName]
        }
      })
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.$parent.$parent.$parent.queryHandle !== undefined) {
        this.$parent.$parent.$parent.$parent.$parent.queryHandle()
      }
    },
    initFormData(data) {
      this.loading = true
      requestAll(`${this.requestPojo.getOnlineFormItemData}${this.queryId}/${data.id}`, 'get').then(response => {
        const resData = response.data
        this.pojo['id'] = resData['id']
        // 附件信息
        this.pojo['filelist'] = resData['filelist']
        // 主表信息
        this.rootItemInfo.map(e => {
          this.pojo[e.field] = resData[e.field]
        })
        for (const i of this.subItemInfo) {
          if (i.relationType === 1) { // 关系一对一
            i.properties.map(subItem => {
              // 给子表一对一对象赋值
              if (resData[i.key][0]) {
                this.pojo[i.key][subItem.field] = resData[i.key][0][subItem.field]
              }
            })
          } else if (i.relationType === 2) { // 关系一对多
             const tbData = resData[i.key]
              tbData.map(tb => {
                const row = []
                i.columns.forEach((e) => {
                  const rowCol = JSON.parse(JSON.stringify(e))
                  rowCol[e.field] = tb[e.field]
                  row.push(rowCol)
                })
                const nTb = JSON.parse(JSON.stringify(tb))
                const nRow = Object.assign(row, nTb)
                this.pojo[i.key].push(nRow)
              })
          }
        }
        this.loading = false
      })
    },
    cancel() {
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
    },
    confirmHandle() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.closeForm()
          this.$emit('receve', this.pojo)
        }
      })
    },
    express(item) {
        return masterJudge(item)
     },
    getVerify(item) {
    return getRules(item)
    }
  }
}
</script>

<style style="scss" scoped>
</style>
